// 删除数据库 链接会断开

class ShuJuKu {
    db = null

    constructor() {
        this.lianJie()
    }
    // 连接数据库
    lianJie() {
        let request = window.indexedDB.open("youXiYuZhou", 1)

        request.onupgradeneeded = (event) => {
            // onupgradeneeded 是我们唯一可以修改数据库结构的地方。在这里面，我们可以创建和删除对象存储以及创建和删除索引。
            // 保存 IDBDatabase 接口
            const db = event.target.result;
          
            // 为数据库创建对象存储（objectStore）
            const objectStore = db.createObjectStore("cunChu", {
                // keyPath: 'a' /* keyPath：存储必须为对象，对象a属性的值为键 */
                // autoIncrement: true,
            });

            // objectStore.createIndex("abc", "abc", { unique: true });
            // 使用事务的 oncomplete 事件确保在插入数据前对象存储已经创建完毕。
            objectStore.transaction.oncomplete = (event) => {
                // const store = db.transaction(["cunChu"], "readwrite").objectStore("cunChu");

                // store.openCursor().onsuccess = (event) => {
                //     const cursor = event.target.result;
                //     if (cursor) {
                //       console.log(`${cursor.key} ${cursor.value}`);
                //       cursor.continue();
                //     } else {
                //       console.log("没有更多记录了！");
                //     }
                // };

                // objectStore.getAll().onsuccess = (event) => {
                //     console.log(`${event.target.result}`);
                // };

                // const index = objectStore.index("abc");
                // index.get("def").onsuccess = (event) => {
                //     console.log(`${event.target.result}`);
                // };

                // index.openCursor().onsuccess = (event) => {
                //     const cursor = event.target.result;
                //     if (cursor) {
                //       console.log(`${cursor.key} ${cursor.value}`);
                //       cursor.continue();
                //     }
                // };

                // const singleKeyRange = window.IDBKeyRange.only("abc");
                // const lowerBoundKeyRange = window.IDBKeyRange.lowerBound("abc"); // >= abc
                // const lowerBoundOpenKeyRange = window.IDBKeyRange.lowerBound("abc", true); // > abc
                // const upperBoundOpenKeyRange = window.IDBKeyRange.upperBound("abc", true); // < abc
                // const boundKeyRange = window.IDBKeyRange.bound("a", "b", false, true); // a <= , < b
                // 默认升序，prev降序
                // index.openCursor(boundKeyRange, "prev").onsuccess = (event) => {
                //     const cursor = event.target.result;
                //     if (cursor) {
                //       // 对匹配结果进行一些操作。
                //       cursor.continue();
                //     }
                // };
                // 第一个参数null不筛选，nextunique过滤重复
                // index.openKeyCursor(null, "nextunique").onsuccess = (event) => {
                //     const cursor = event.target.result;
                //     if (cursor) {
                //       // 对记录进行一些操作。
                //       cursor.continue();
                //     }
                // };

                // index.openKeyCursor().onsuccess = (event) => {
                //     const cursor = event.target.result;
                //     if (cursor) {
                //       console.log(`${cursor.key} ${cursor.primaryKey}`);
                //       cursor.continue();
                //     }
                // };
                
            };
        };

        return new Promise((resolve, reject) => {
            request.onsuccess = (event) => {
                this.db = event.target.result;
    
                this.db.onerror = (event) => {
                    console.error(event);
                };

                resolve(event.target.result)
            };

            request.onerror = (event) => {
                console.error(event);

                reject()
            };
        })
    }

    async zengJia(zhi, jian) {
        if (this.db === null) await this.lianJie()

        let request = this.db.transaction(["cunChu"], "readwrite").objectStore("cunChu").add(zhi, jian);
       
        return new Promise(resolve => {
            request.onsuccess = (event) => {
                resolve()
            };
        })
    }

    async chaXun(jian) {
        if (this.db === null) await this.lianJie()

        let request = this.db.transaction(["cunChu"], "readonly").objectStore("cunChu").get(jian);
       
        return new Promise(resolve => {
            request.onsuccess = (event) => {
                resolve(event.target.result)
            };
        })
    }

    async xiuGai(zhi, jian) {
        if (this.db === null) await this.lianJie()
        
        let request = this.db.transaction(["cunChu"], "readwrite").objectStore("cunChu").put(zhi, jian);
       
        return new Promise(resolve => {
            request.onsuccess = (event) => {
                resolve()
            };
        })
    }

    async shanChu(jian) {
        let request = this.db.transaction(["cunChu"], "readwrite").objectStore("cunChu").delete(jian);
       
        return new Promise(resolve => {
            request.onsuccess = (event) => {
                resolve()
            };
        })
    }
}

export {
    ShuJuKu
}